﻿/*
 * udpclientdevice.cpp
 *
 *  Created on: 2017年2月22日
 *      Author: work
 */

#include <dm/export.hpp>

#define DM_API_OS_COM DM_API_EXPORT

#include <dm/os/com/udpclientdevice.hpp>
#include <dm/os/log/logger.hpp>

namespace dm{
namespace os{
namespace com{

using namespace boost::asio;

static const char* logModule = "CUdpClientDevice.com.os.dm";

CUdpClientDevice::CUdpClientDevice( ios_t& ios,const size_t& rxBufSize ):
		CDevice(rxBufSize),m_dev(ios){
	log().debug(THISMODULE "创建对象");
}

CUdpClientDevice::~CUdpClientDevice(){
	log().debug(THISMODULE "销毁对象");
	m_dev.shutdown(m_dev.shutdown_both);
	m_dev.close();
}

bool CUdpClientDevice::onConnected(){
	start_rx();

	log().debug(THISMODULE "测试，发送hello");
	return asynSend((const dm::uint8*)"hello",6);
}

bool CUdpClientDevice::checkAndSetAddress( const CUdpClientAddr& addr ){
	m_addr = addr;
	return true;
}

bool CUdpClientDevice::startConnect(){
	const CUdpClientAddr* addr = m_addr.asUdpClient();
	if( !addr ){
		log().warnning(THISMODULE "没有可用地址");
		return false;
	}

	m_dev.open(ip::udp::v4());
	m_peer.address(ip::address::from_string(addr->getServerHost().c_str()));
	m_peer.port(addr->getServerPort());

	handler_connect();
	return true;
}

bool CUdpClientDevice::stopConnect(){
	m_dev.close();
	handler_disconnect();
	return true;
}

bool CUdpClientDevice::startSend( const uint8* buf,const size_t& len ){
	m_dev.async_send_to(buffer(buf,len),m_peer,
			boost::bind(&CUdpClientDevice::handler_tx,this,placeholders::error)
			);
	return true;
}

void CUdpClientDevice::start_rx(){
	m_dev.async_receive( buffer(m_rxBuf.get(),m_rxBufSize),
			boost::bind(&CUdpClientDevice::handler_rx,this,
					placeholders::error,
					placeholders::bytes_transferred)
	);
}

void CUdpClientDevice::cancelDev(){
	m_dev.cancel();
}
}
}
}


